//消息

interface ImessageViewModel extends ng.IScope {
    /**
     * 消息数据
     */
    MessageList : messageList[];
    messageList:Array<MessageListItemResponse>;
    /**
     * 页码
     */
    currentPage:number;
    /**
     * 下一页
     */
    // nextPage():void;
    /**
     * 上一页
     */
    // prevPage():void;
    /**
     * 选中页码翻页
     */
    // setPage(pageNumber:number):void;
    /**
     * 总数据数
     */
    totalNumber:number;
    /**
     * 页码数分页
     */
    // pageNum:number[];
    /**
     * 删除单条
     */
    Thisdel(key):void;
    /**
     * 清空
     */
    Alldel():void;

    pageChanged(page:number):void;
    totalItems:number;
    max:number

}
interface ImessageRootScopt extends ng.IRootScopeService{
    unReadList:Array<MessageListItemResponse>;//messageList[];
    messageTotal:number
}

interface messageList {
    Content: string,
    InvalidTime: string,
    Time: string,
    Type: string,
    key: string,
    isRead?:number;
}

class messageController {
    // wilddogUrl:string;
    // evaluatRef:any;
    startTime:string[] = [];
    endTime:string[] = [];
    nextKey:string = "";
    prevkey:string = "";
    lastKey:string = "";
    lock:boolean;

    //消息接收人
    notifier:string;

    constructor(private $scope: ImessageViewModel, private $rootScope: ImessageRootScopt,private routeService: routeService, private $ngBootbox: BootboxService,
        private $state:ng.ui.IStateService,private messageService:IMessageService) {
        // this.wilddogUrl = window.localStorage.getItem("refEvaluateShipOrder")
        // this.evaluatRef = new Wilddog(this.wilddogUrl);
        this.$scope.messageList = [];
        // this.$rootScope.unRedaList = [];
       
        this.init();
        
        this.lock = true;
    }
    init():void{
        // 野狗修改
        this.$scope.max=5;
        this.$scope.totalItems= 5;
        this.$scope.currentPage = 0;

        // this.$rootScope.unRedaList = [];

        this.notifier =  JSON.parse(localStorage.getItem("loginData")).id;

        

        

        this.$scope.pageChanged = this.pageChanged;
        //删除单条
        this.$scope.Thisdel  = this.Thisdel
        //删除全部
        this.$scope.Alldel = this.Alldel


        // this.$scope.currentPage = 0;
        //子节点个数
        // this.evaluatRef.on("value", (snapshot)=> {
        //     snapshot.numChildren() === 0 ? this.$scope.totalNumber = 0 : this.$scope.totalNumber = snapshot.numChildren();
        //     this.pagetotal();
        //     this.getPageTime();
        // });
        // this.$scope.setPage = (pageNumber)=>{
        //      this.setPage(pageNumber);
        // }
        // this.nextPageFn(null);
        // this.$scope.nextPage = this.nextPage;
        // this.$scope.prevPage = this.prevPage;
        // this.$scope.Thisdel = (key:string)=>{
        //      this.Thisdel(key)
        // }
        // this.$scope.Alldel = this.Alldel;

        // this.$scope.$on("$destroy",()=>{
        //     this.destroy();
        // })
        // this.evaluatRef.on("child_changed",(snapshot)=>{
        //    if(!this.lock){return} 
        //    this.$scope.currentPage = 0;
        //    var getMess = this.evaluatRef.orderByChild("Time").endAt(String(new Date)).limitToLast(6).on("value",(snapshot)=>{
        //         this.$scope.messageList = [];
        //         this.evaluatRef.off('value',getMess);
        //          snapshot.forEach((snap)=>{
        //             if (!snap.val().Content) { this.evaluatRef.child(snap.key()).remove(); };
        //             if (this.$scope.messageList.length < 6) {
        //                 this.$scope.messageList.push({
        //                     Content: snap.val().Content,
        //                     InvalidTime: snap.val().InvalidTime,
        //                     Time: snap.val().Time,
        //                     Type: snap.val().Type,
        //                     isRead: snap.val().isRead,
        //                     key: snap.key()
        //                 });
        //                 this.nextKey = this.$scope.messageList[0].Time;
        //                 this.prevkey = snap.val().Time;
        //                 if(String(this.$state.current.url).indexOf("/messageList")!=-1){
        //                     this.alterRead(snap.key(), snap.val().isRead);
        //                 }
        //             }
        //          });
        //          if(this.$scope.messageList.length >5){
        //             this.$scope.messageList.splice(0, 1);
        //          }
        //     });
        //     this.getUnread();
        //     this.refreshMessage();
        // });
        this.getMessage(0,5)
    };

    // 野狗修改：获取列表消息
    getMessage=(skip:number,count:number,page?:number)=>{
        this.messageService.getList(this.notifier,null,skip,count).then((res)=>{
            // console.log('res',res);
            this.$scope.totalNumber = res.data.total;
            this.$scope.messageList = res.data.data;
            if(!page){page =0}else{
                page = page -1;
            }
            this.$scope.totalItems = this.$scope.totalNumber;

            //刷新下获取未读消息列表
            this.messageService.getList(this.notifier,false,0,5).then((res)=>{
                this.$rootScope.unReadList = res.data.data;
            })

            //未读数量
            this.messageService.getNoReadSystemNotifyCount(this.notifier).then(res=>{
                // console.log('当',res.data.extData)
                this.$rootScope.messageTotal = res.data.extData
            })
        

        })
    }

    /**
     * 野狗修改：分页
     */
    pageChanged=(page:number)=>{
        var currentPage = (page -1 )* this.$scope.max ;
        this.getMessage( currentPage ,5,page);
    }



    //分页
    // pagetotal=()=>{
    //     this.$scope.pageNum = [];
    //     for (var n = 0; n < this.$scope.totalNumber / 5; n++) {
    //         this.$scope.pageNum.push(n);
    //     }
    // }
    /**
     * 获取全部数据分页位置
     */
    // getPageTime=()=>{
    //     for (var i = 0; i < Math.ceil(this.$scope.totalNumber / 5) - 1 ; i++) {
    //         this.evaluatRef.orderByChild("Time").endAt(i==0?String(new Date):this.startTime[i-1]).limitToLast(6).on('value',(snapshot)=>{
    //             var num = 0;
    //             snapshot.forEach((snap)=>{
    //                 num++;
    //                 if (num == 1) {
    //                     this.lastKey = snap.val().Time;
    //                     this.startTime.push(snap.val().Time)
    //                 } else if (num == 6) {
    //                     this.endTime.push(snap.val().Time)
    //                 }
    //             });
    //         });
    //     }
    // }

    /**
     * 下一页
     */
    // nextPage=()=>{
    //     if (this.$scope.currentPage == Math.ceil(this.$scope.totalNumber / 5) - 1) {
    //         return
    //     } else {
    //         this.lock = false
    //         this.$scope.currentPage++;
    //         this.nextPageFn(null);
    //         this.getUnread();
    //     }
    // }
    /**
     * 上一页
     */
    // prevPage=()=>{
    //     if (this.$scope.currentPage < 1) {
    //         return
    //     } else {
    //         this.$scope.currentPage--;
    //         this.prevPageFn();
    //         this.getUnread();
    //     }
    // }

    /**
     * 选中页码翻页
     */
    // setPage=(pageNumber:number)=>{
    //     this.$scope.currentPage = pageNumber;
    //     this.checkedPack(pageNumber)
    // }

    /**
     * 刷新未读消息
     */
    getUnread=()=>{
        // var getUnread = this.evaluatRef.orderByChild("isRead").equalTo(0).limitToFirst(99).on("value",(snapshot)=> {
        //     // this.evaluatRef.off("value", getUnread)
        //     this.$rootScope.unRedaList = [];
        //     snapshot.forEach((snap)=>{
        //         this.$rootScope.unRedaList.push({
        //             Content: snap.val().Content,
        //             InvalidTime: snap.val().InvalidTime,
        //             Time: snap.val().Time,
        //             Type: snap.val().Type,
        //             key: snap.key()
        //         });
        //     })
        // });
    }

    /**
     * 下一页
     */
    // nextPageFn=(isRemove:boolean)=>{
    //     if (isRemove) { this.nextKey = "" };
    //     var nextPage = this.evaluatRef.orderByChild("Time").endAt(this.nextKey == "" || !this.nextKey ? String(new Date) : this.nextKey).limitToLast(6).on("value",(snapshot)=>{
    //         this.$scope.messageList.length = 0;
    //         this.evaluatRef.off('value', nextPage);
    //         snapshot.forEach((snap)=>{
    //             if (!snap.val().Content) { this.evaluatRef.child(snap.key()).remove(); };
    //             if (this.$scope.messageList.length < 6) {
    //                 if(this.$scope.messageList.length >0){
    //                      this.alterRead(snap.key(), snap.val().isRead);
    //                 }else{
    //                     if(snap.val().isRead==0){
    //                         this.alterRead(snap.key(), snap.val().isRead);
    //                     }
    //                 }
    //                 this.$scope.messageList.push({
    //                     Content: snap.val().Content,
    //                     InvalidTime: snap.val().InvalidTime,
    //                     Time: snap.val().Time,
    //                     Type: snap.val().Type,
    //                     isRead: snap.val().isRead,
    //                     key: snap.key()
    //                 });
    //                 this.nextKey = this.$scope.messageList[0].Time;
    //                 this.prevkey = snap.val().Time;
    //             }
    //             if (this.$scope.currentPage === Math.ceil(this.$scope.totalNumber / 5) - 1) {
    //                 this.prevkey = this.$scope.messageList[this.$scope.messageList.length-1].Time;
    //             }
    //         });
    //         if (this.$scope.currentPage !== Math.ceil(this.$scope.totalNumber / 5) - 1) {
    //             this.$scope.messageList.splice(0, 1);
    //         }
    //     })
    //      this.lock = true;
    // }

    /**
     * 修改成已读
     */
    alterRead=(key:string, isRead:number)=>{
        // if (isRead == 0) {
        //     var childRef = new Wilddog(this.routeService.getWilddogUrl() + JSON.parse(window.localStorage.getItem("loginData")).id + "/" + 1 + "/" + "0/" + key);
        //     childRef.update({
        //         isRead: 1
        //     });
        // }
        // this.evaluatRef.off('value');
        // this.evaluatRef.orderByChild("isRead").equalTo(0).once("value",(snapshot)=>{
        //     this.$rootScope.messageTotal = snapshot.numChildren();
        // });
    }

    prevPageFn=()=>{
        // var prevPageFn = this.evaluatRef.orderByChild("Time").startAt(this.prevkey == "" ? String(new Date) : this.prevkey).limitToFirst(6).on('value', (snapshot)=> {
        //     this.$scope.messageList.length = 0;
        //     this.evaluatRef.off('value', prevPageFn);
        //     snapshot.forEach((snap)=>{
        //         if (!snap.val().Content) { this.evaluatRef.child(snap.key()).remove(); };
        //         if (this.$scope.messageList.length < 6) {
        //             //修改成已读
        //             this.alterRead(snap.key(), snap.val().isRead);
        //             this.$scope.messageList.push({
        //                 Content: snap.val().Content,
        //                 InvalidTime: snap.val().InvalidTime,
        //                 Time: snap.val().Time,
        //                 Type: snap.val().Type,
        //                 isRead:snap.val().isRead,
        //                 key: snap.key()
        //             });
        //             this.nextKey = this.$scope.messageList[0].Time;
        //             this.prevkey = snap.val().Time;
        //         }
        //         if (this.$scope.currentPage === Math.ceil(this.$scope.totalNumber / 5) - 1) {
        //             this.prevkey = this.$scope.messageList[this.$scope.messageList.length - 1].Time;
        //         }
        //     });
        //     if (this.$scope.currentPage !== Math.ceil(this.$scope.totalNumber / 5) - 1) {
        //         this.$scope.messageList.splice(0, 1);
        //     }
        // });
    }
    
    /**
     * 获取页面位置
     */
    checkedPack=(page:number)=>{
        this.lock = false
        this.getManage(page);
        this.getUnread();
    }

    /**
     * 获取选中页面数
     */
    getManage=(page:number)=>{
        // var getManage = this.evaluatRef.orderByChild("Time").endAt(!this.startTime[page - 1] ? String(new Date) : this.startTime[page - 1]).limitToLast(6).on("value",(snapshot)=> {
        //     this.$scope.messageList.length = 0;
        //     this.evaluatRef.off('value', getManage);
        //     snapshot.forEach((snap)=>{
        //         if (!snap.val().Content) { this.evaluatRef.child(snap.key()).remove(); };
        //         if (this.$scope.messageList.length < 6) {
        //             if(this.$scope.messageList.length >0){
        //                  this.alterRead(snap.key(), snap.val().isRead);
        //             }
        //             this.$scope.messageList.push({
        //                 Content: snap.val().Content,
        //                 InvalidTime: snap.val().InvalidTime,
        //                 Time: snap.val().Time,
        //                 Type: snap.val().Type,
        //                 key: snap.key()
        //             });
        //             this.nextKey = this.$scope.messageList[0].Time;
        //             this.prevkey = snap.val().Time;
        //         }
        //     });
        //     if (this.$scope.currentPage !== Math.ceil(this.$scope.totalNumber / 5) - 1) {
        //         this.$scope.messageList.splice(0, 1);
        //     }
        // });
        // this.lock = true;
    }

    /**
     * 删除单条消息
     */
    Thisdel=(key:string)=>{
        this.$scope.currentPage = 0;
        this.$ngBootbox.confirm("是否删除此消息？").then(e => {
            this.messageService.deleteById(key).then(result => {
                // 刷新列表
                this.getMessage(0,5)
            });
        });

        // this.evaluatRef.child(key).remove();
        // this.evaluatRef.once("value", (snapshot)=>{
        //     snapshot.numChildren() === 0 ? this.$scope.totalNumber = 0 : this.$scope.totalNumber = snapshot.numChildren();
        //     this.pagetotal();
        // });
        // this.$scope.currentPage = 0;
        // this.nextPageFn(true);
    }

    /**
     * 清空消息
     */
    Alldel=()=>{
        this.$scope.currentPage = 0;
        this.$ngBootbox.confirm("确认清空消息吗？").then( e => {
            this.messageService.deleteByNotifier(this.notifier).then(res=>{
                //刷新列表
                this.getMessage(0,5)
            })
        });

        // this.$ngBootbox.confirm('确认清空消息吗?').then(()=> {
        //     this.evaluatRef.remove();
        //     this.evaluatRef.once("value", (snapshot)=>{
        //         snapshot.numChildren() === 0 ? this.$scope.totalNumber = 0 : this.$scope.totalNumber = snapshot.numChildren();
        //         this.pagetotal();
        //     });
        //     this.$scope.messageList.length = 0;
        // });
    }

    /**
     * 离开页面触发
     */
    destroy=()=>{
        // this.evaluatRef.off('value');
        // this.evaluatRef.orderByChild("isRead").equalTo(0).on("value",(snapshot)=>{
        //     this.$rootScope.messageTotal = snapshot.numChildren();
        // });
        // this.evaluatRef.orderByChild("isRead").equalTo(0).limitToFirst(99).on("value",(snapshot)=>{
        //     this.$rootScope.unRedaList = [];
        //     snapshot.forEach((snap)=>{
        //         this.$rootScope.unRedaList.push({
        //             Content: snap.val().Content,
        //             InvalidTime: snap.val().InvalidTime,
        //             Time: snap.val().Time,
        //             Type: snap.val().Type,
        //             key: snap.key()
        //         });
        //     })
        // });
    }
    /**
     * 刷新消息数
     */
    refreshMessage=()=>{
        // this.evaluatRef.orderByChild("isRead").equalTo(0).on("value",(snapshot)=>{
        //     this.$rootScope.messageTotal = snapshot.numChildren();
        // });
        // this.evaluatRef.on("value", (snapshot)=> {
        //     snapshot.numChildren() === 0 ? this.$scope.totalNumber = 0 : this.$scope.totalNumber = snapshot.numChildren();
        // });
    }
    
}

angular.module("tms").controller("messageController", ["$scope","$rootScope",'routeService', "$ngBootbox","$state","messageService", messageController]);
